﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.UI;

namespace jQueryDotNetLib
{
    public class Utility
    {
        private static System.Text.RegularExpressions.Regex selectorRegExp = new System.Text.RegularExpressions.Regex(@"\{\w+\}", System.Text.RegularExpressions.RegexOptions.Compiled);
        private static object _lock = new object();
        public static string ResolveSelectors(string SelectorString, ControlCollection ControlCollectionRoot)
        {
            lock (_lock)
            {
                System.Text.RegularExpressions.MatchCollection matchList = selectorRegExp.Matches(SelectorString);
                foreach (System.Text.RegularExpressions.Match m in matchList)
                {
                    string ControlID = m.Value.Substring(1, m.Value.Length - 2);
                    Control ctl = FindControlRecursive(ControlCollectionRoot, ControlID);
                    if (ctl == null)
                    {
                        System.Web.UI.Page p = (System.Web.HttpContext.Current.Handler as System.Web.UI.Page);
                        if (p != null)
                        {
                            if (p.Master == null)
                                ctl = FindControlRecursive(p.Controls, ControlID);
                            else
                                ctl = FindControlRecursive(p.Master.Controls, ControlID);
                        }

                        if(ctl==null) throw new System.NotSupportedException(string.Format("You must provide a valid Server Control ID, could not resolve: {0}", ControlID));
                    }
                    SelectorString = SelectorString.Replace(m.Value, ctl.ClientID);

                }
            }
            return SelectorString;
        }


        private static Control FindControlRecursive(ControlCollection PageList, ControlCollection MasterPageList, string ServerID)
        {
            if (MasterPageList != null && MasterPageList.Count > 0) return FindControlRecursive(MasterPageList, ServerID);
            return FindControlRecursive(PageList, ServerID);
        }
        private static Control FindControlRecursive(ControlCollection List, string ServerID)
        {
            Control ctl = null;
            if (List != null && List.Count > 0)
            {
                if (ctl == null)
                {
                    foreach (Control c in List)
                    {
                        if (c.ID == ServerID)
                        {
                            ctl = c;
                            break;
                        }
                        ctl = FindControlRecursive(c.Controls, ServerID);
                        if (ctl != null) break;
                    }
                }
            }
            return ctl;
        }
    }
}
